package com.example.gmranqi.common.conver;

import java.io.*;
import java.util.Map;

/**
 * Blob数据类型转换工具
 * 
 * @author 高总辉
 */
public class BlobUtils {

	/**
	 * 
	 * @param data
	 *            待转换byte的数组
	 * @return 转换为HashMap的对象
	 * @throws Exception
	 *             转换异常
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, String> blobConvertMap(byte[] data) throws Exception {
		Map<String, String> map = null;
		ByteArrayInputStream bais = null;
		ObjectInputStream ois = null;
		try {
			bais = new ByteArrayInputStream(data);
			ois = new ObjectInputStream(bais);
			map = (Map<String, String>) ois.readObject();
		} catch (Exception e) {

		} finally {
			if (ois != null) {
				ois.close();
			}
			if (bais != null) {
				bais.close();
			}
		}
		return map;
	}

	/**
	 * 
	 * @param data
	 *            待转换Map对象
	 * @return 转换为byte的数组
	 * @throws Exception
	 *             转换异常
	 */
	public static byte[] MapConvertBlob(Map<String, String> data) throws Exception {
		byte[] bytes = null;
		ByteArrayOutputStream baos = null;
		ObjectOutputStream oos = null;
		try {
			baos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(baos);
			oos.writeObject(data);
			bytes = baos.toByteArray();
		} catch (Exception e) {

		} finally {
			if (oos != null) {
				oos.close();
			}
			if (baos != null) {
				baos.close();
			}
		}
		return bytes;
	}

	/**
	 * 
	 * @param data
	 *            待转换byte的数组
	 * @return 转换为String的对象
	 * @throws Exception
	 *             转换异常
	 */
	public static String blobConvertString(byte[] data) throws Exception {
		StringBuilder sb = new StringBuilder();
		ByteArrayInputStream bais = null;
		BufferedReader br = null;
		try {
			bais = new ByteArrayInputStream(data);
			br = new BufferedReader(new InputStreamReader(bais));
			String line = null;
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
		} catch (Exception e) {

		} finally {
			if (br != null) {
				br.close();
			}
			if (bais != null) {
				bais.close();
			}
		}
		return sb.toString();
	}

	/**
	 * 
	 * @param data
	 *            待转换String对象
	 * @return 转换为byte的数组
	 * @throws Exception
	 *             转换异常
	 */
	public static byte[] StringConvertBlob(String data) throws Exception {
		byte[] bytes = null;
		ByteArrayOutputStream baos = null;
		BufferedWriter bw = null;
		try {
			baos = new ByteArrayOutputStream();
			bw = new BufferedWriter(new OutputStreamWriter(baos));
			bw.write(data);
			bytes = baos.toByteArray();
		} catch (Exception e) {

		} finally {
			if (bw != null) {
				bw.close();
			}
			if (baos != null) {
				baos.close();
			}
		}
		return bytes;
	}

}
